package com.wwwarehouse.taskcenter.fragment.bluetooth;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.BluetoothBean;
import com.wwwarehouse.common.eventbus_event.ConnectEvent;
import com.wwwarehouse.common.eventbus_event.ConnectSuccessEvent;
import com.wwwarehouse.common.eventbus_event.ConnectingEvent;
import com.wwwarehouse.common.eventbus_event.DisConnectedEvent;
import com.wwwarehouse.common.eventbus_event.ScanEvent;
import com.wwwarehouse.common.service.BluetoothService;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.adapter.BluetoothListAdapter;
import com.wwwarehouse.taskcenter.eventbus_event.ToConnectEvent;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Description:
 * Copyright  : Copyright (c) 2017
 * Author     : yfwang
 * Date       : 2017/9/29 10:11
 */
public class BluetoothFragment extends BaseFragment {

    private LinearLayout mTips;
    private RecyclerView mBleList;
    private BluetoothAdapter bluetoothAdapter;
    private Intent intent;
    private ArrayList<BluetoothBean> bluetoothBeen;
    private ArrayList<String> bluetoothMac;
    private BluetoothListAdapter adapter;
    private int position;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ble, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mTips = (LinearLayout) view.findViewById(R.id.ll_tips);
        mBleList = (RecyclerView) view.findViewById(R.id.rv_blelist);
        EventBus.getDefault().register(this);
        BluetoothManager bluetoothManager = (BluetoothManager) mActivity.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        checkPermissions();

        bluetoothBeen = new ArrayList<>();
        bluetoothMac = new ArrayList<>();
        adapter = new BluetoothListAdapter(mActivity);
        adapter.setData(bluetoothBeen);
        mBleList.setLayoutManager(new LinearLayoutManager(mActivity));
        mBleList.setAdapter(adapter);



    }

    public void onEventMainThread(Object event) {

        if (event != null && event instanceof ScanEvent) {
            if (!bluetoothMac.contains(((ScanEvent) event).getResult().getAddress())) {
                bluetoothMac.add(((ScanEvent) event).getResult().getAddress());
                bluetoothBeen.add(((ScanEvent) event).getResult());
                adapter.notifyDataSetChanged();
            }
        } else if (event != null && event instanceof ConnectSuccessEvent) {
            //连接成功
            bluetoothBeen.get(position).setState("ConnectSuccess");
            adapter.notifyItemChanged(position);
            popFragment();
            toast(R.string.connected);
        } else if (event != null && event instanceof DisConnectedEvent) {
            //断开连接
            mTips.setVisibility(View.VISIBLE);
            mBleList.setVisibility(View.GONE);
            bluetoothBeen.get(position).setState("DisConnected");
            adapter.notifyItemChanged(position);
            LogUtils.showLog("BluetoothFragment----->DisConnected");
            toast(R.string.disconnect);
        }else if (event instanceof ConnectingEvent){
            bluetoothBeen.get(position).setState("Connecting");
            LogUtils.showLog("BluetoothFragment----->Connecting");
            adapter.notifyItemChanged(position);
        } else if (event instanceof ToConnectEvent){
            EventBus.getDefault().post(new ConnectEvent(((ToConnectEvent) event).getResult().getAddress()));
            position = ((ToConnectEvent) event).getPosition();
        }


    }

    private void checkPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(mActivity, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(mActivity, deniedPermissions, 12);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (!bluetoothAdapter.enable()) {
                    mTips.setVisibility(View.VISIBLE);
                    mBleList.setVisibility(View.GONE);
                } else {
                    mTips.setVisibility(View.GONE);
                    mBleList.setVisibility(View.VISIBLE);
                }
                IntentFilter intent = new IntentFilter();
                intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
                intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//动作状态发生了变化
                mActivity.registerReceiver(mReceiver, intent);
                startService();
                break;
        }
    }


    private void startService() {
        intent = new Intent(mActivity, BluetoothService.class);
        mActivity.startService(intent);
    }


    @Override
    public void setTitle() {
        if (peekFragment() instanceof BluetoothFragment) {
            mActivity.setTitle(getString(R.string.conn_bluetooth));
        }
    }

    @Override
    public void requestDatas() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (intent != null)
            mActivity.stopService(intent);
    }



    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch(intent.getAction()){
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch(blueState){
                        case BluetoothAdapter.STATE_TURNING_ON:
                            mTips.setVisibility(View.GONE);
                            mBleList.setVisibility(View.VISIBLE);
                            startService();
                            break;
                        case BluetoothAdapter.STATE_ON:
                            mTips.setVisibility(View.GONE);
                            mBleList.setVisibility(View.VISIBLE);
                            startService();
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            mTips.setVisibility(View.VISIBLE);
                            mBleList.setVisibility(View.GONE);
                            break;
                        case BluetoothAdapter.STATE_OFF:
                            mTips.setVisibility(View.VISIBLE);
                            mBleList.setVisibility(View.GONE);
                            break;

                    }
                    break;
            }
        }
    };


}
